//
//  NewsDetailViewController.m
//  coba-iOS
//
//  Created by 郭四虎 on 15/12/9.
//  Copyright © 2015年 YouKu. All rights reserved.
//

#import "NewsDetailViewController.h"

@interface NewsDetailViewController ()<WKNavigationDelegate,UIWebViewDelegate,GDTMobBannerViewDelegate>
{
    UIWebView *_webView;
    //WKWebView *_webView;
    UIImageView *_imaView;
    UIView *_backView;
    
    BOOL _statusBarHidden;
}
@property (strong, nonatomic) GDTMobBannerView *bannerView;

@end

@implementation NewsDetailViewController

- (GDTMobBannerView *)bannerView
{
    if (!_bannerView) {
        _bannerView = [[GDTMobBannerView alloc] initWithFrame:CGRectMake(0, 0,
                                                                         GDTMOB_AD_SUGGEST_SIZE_320x50.width*SCALEX,
                                                                         GDTMOB_AD_SUGGEST_SIZE_320x50.height) appkey:GGTID placementId:@"2000315186157072"];
        
        // 设置广告视图的位置 宽与高设置为0即可 该广告视图默认是横竖屏自适应 但需要在旋转时调用orientationChanged 方法
        // Set the frame of advertisement view
        _bannerView.delegate = self;
        _bannerView.currentViewController = self; //设置当前的ViewController
        _bannerView.interval = 30; //【可选】设置刷新频率;默认30秒
        _bannerView.isGpsOn = NO; //【可选】开启GPS定位;默认关闭
        //_bannerView.showCloseBtn = NO; //【可选】展示关闭按钮;默认显示
        _bannerView.isAnimationOn = YES; //【可选】开启banner轮播和展现时的动画效果;默认开启
        
        [_bannerView loadAdAndShow];
    }
    return _bannerView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"新闻详情";
    self.view.backgroundColor = [UIColor whiteColor];
    
    CGRect rect = SCREEN;
    rect.origin.y += 64;
    rect.size.height -= 64+GDTMOB_AD_SUGGEST_SIZE_320x50.height;

//    NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
//    
//    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
//    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
//    [wkUController addUserScript:wkUScript];
//    
//    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
//    wkWebConfig.userContentController = wkUController;
    
    _webView = [[UIWebView alloc]initWithFrame:rect];
    //_webView.navigationDelegate = self;
    _webView.delegate = self;
    //_webView.scrollView.delegate = self;
    _webView.backgroundColor = [UIColor clearColor];
    
    [_webView setOpaque:NO];
    
    [self.view addSubview:_webView];
        //_webView.scalesPageToFit = YES;
    
    self.bannerView.y = _webView.bottom;
    [self.view addSubview:self.bannerView];
    [self createData];
    
    
//    unsigned int propCount = 0;
//    objc_property_t *properties = class_copyPropertyList([_model class], &propCount);
//    
//    for(int idx = 0; idx < propCount; idx++) {
//        objc_property_t prop = *(properties + idx);
//        NSString *key = @(property_getName(prop));
//        NSString *key2 = @(property_getAttributes(prop));
//        NSString *key3 = [_model valueForKey:key];
//        NSLog(@"%@::%@::%@", key,key2,key3);
//
//    }
}



- (void)createData
{
    //http://test4.cooba.cc/index.php/Port/newsPortInfoDetail
    
    NSString *url;
    if ([ISBUS boolValue]) {
        url = [NSString stringWithFormat:@"%@/Port/newsPortInfoDetail",CAR_URL];
        [self post:url back:^(NSError *error) {
        
        }];
    }else{
        url = NEWSDETAIL;
        [self post:url back:^(NSError *error) {
           
        }];
    }    
}

- (void)post:(NSString *)url back:(void(^)(NSError *))back
{
    NSDictionary *parameter = @{@"id":_model.newsid,@"dir_name":_model.dir_name};
    
    [MyAFN POST:url parameters:parameter block:^(id responseObject) {
        
        NSDictionary *response = responseObject;
        if ([[response objectForKey:@"status"]integerValue]) {
            
            NSString *html = [response objectForKey:@"content"];
            
           // NSString *html = [NSString stringWithFormat:@"<html><head></head><body style=\"font-size: 18px\">%@</body></html>", [response objectForKey:@"content"]];
            
            //NSLog(@"%@",html);
            
            // NSString *string = [html stringByReplacingOccurrencesOfString:@"src=\"" withString:@"src=\"http://test4.cooba.cc/"];
            
            NSString *dateStr;
            if ([ISBUS boolValue]) {
                dateStr = [response objectForKey:@"create_time"];
            }else{
                dateStr = [MyDateformater formater:[response objectForKey:@"create_time"]];
            }
            
//            NSString *str = [NSString stringWithFormat:@"<h3 style=\"text-align:center\">%@</h3><span>%@</span><span style=\"margin-left:20px;\">%@</span><head><style>img{max-width:100%%;height:auto; !important;}</style></head>%@",[response objectForKey:@"title"],dateStr,[response objectForKey:@"author"],html];
//            
//            NSString * strr = [NSString stringWithFormat:@"<html><head></head><body style=\"font-size: 18px;\">%@</body></html>",str];
            
            
            NSString *str = [NSString stringWithFormat:@"<head><style>img{width:100%%;height:auto; !important;}</style></head>"];
            
            NSString * strr = [NSString stringWithFormat:@"<html>%@<body style=\"font-size: 18px;color:#555555;text-align:justify;text-justify:inter-ideograph;line-height:1.5\"><h3 style=\"text-align:center;color:black\">%@</h3><span>%@</span><span style=\"margin-left:20px;\">%@</span>%@</body></html>",str,[response objectForKey:@"title"],dateStr,[response objectForKey:@"author"],html];
            
            
            [_webView loadHTMLString:strr baseURL:nil];
        }
    }error:^(NSError *error) {
        back(error);
    }fromController:self];
}


- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //CGFloat webViewHeight = 0.0f;
    
    //webViewHeight = webView.scrollView.contentSize.height;

    static  NSString * const jsGetImages =
    
    @"function getImages(){\
    var objs = document.getElementsByTagName(\"img\");\
    for(var i=0;i<objs.length;i++){\
    objs[i].onclick=function(){\
    document.location=\"myweb:imageClick:\"+this.src;\
    };\
    };\
    return objs.length;\
    };";
    
    [webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法
    
    //注入自定义的js方法后别忘了调用 否则不会生效（不调用也一样生效了，，，不明白）
    [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];
    //调用js方法
    //NSLog(@"---调用js方法--%@  %s  jsMehtods_result = %@",self.class,__func__,resurlt);
    
    NSString * GetImages = [NSString stringWithFormat:
                              
                              @"function Images(){\
                              var objs = document.getElementsByTagName(\"img\");\
                              for(var i=0;i<objs.length;i++){\
                              objs[i].style.width = \"%fpx\";\
                              };\
                              \
                              };",WIDTH-20];
    
    [webView stringByEvaluatingJavaScriptFromString:GetImages];//注入js方法
    
    //注入自定义的js方法后别忘了调用 否则不会生效（不调用也一样生效了，，，不明白）
    [webView stringByEvaluatingJavaScriptFromString:@"Images()"];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    //将url转换为string
    NSString *requestString = [[request URL] absoluteString];
    //    NSLog(@"requestString is %@",requestString);
    
    //hasPrefix 判断创建的字符串内容是否以pic:字符开始
    if ([requestString hasPrefix:@"myweb:imageClick:"]) {
        NSString *imageUrl = [requestString substringFromIndex:@"myweb:imageClick:".length];
        //        NSLog(@"image url------%@", imageUrl);
        
        [self showImage:imageUrl];
        return NO;
    }
    return YES;
}

- (BOOL)prefersStatusBarHidden
{
    if (_statusBarHidden) {
        return YES;
    }else{
        return NO;
    }
}

- (void)showImage:(NSString *)imageUrl
{
    _statusBarHidden = YES;
    [self prefersStatusBarHidden];
    
    if (!_imaView|!_backView) {
        _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
        _backView.backgroundColor = [UIColor blackColor];
        _backView.hidden = YES;
        
        _imaView = [[UIImageView alloc]initWithFrame:CGRectZero];
        _imaView.userInteractionEnabled = YES;
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(WIDTH - 100, HEIGHT - 50, 100, 50);
        [btn setTitle:@"保存" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(saveIma) forControlEvents:UIControlEventTouchUpInside];
        
        
        [_backView addSubview:_imaView];
        [_backView addSubview:btn];
        
        UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinch:)];
        [_imaView addGestureRecognizer:pinch];
        
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(moveIma:)];
        [_imaView addGestureRecognizer:pan];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hidIma)];
        [_backView addGestureRecognizer:tap];
    }
    
    _backView.hidden = NO;
    _backView.alpha = 0;
    [self.view addSubview:_backView];
    [UIView animateWithDuration:0.2 animations:^{
        
        _backView.alpha = 1;
    }];
    
    
    [_imaView sd_setImageWithURL:[NSURL URLWithString:imageUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        if (!image) {
            return;
        }
        
        if (image.size.width>= image.size.height) {
            
            _imaView.frame = CGRectMake(0, 0, WIDTH, image.size.height/image.size.width*WIDTH);
        }else{
            if (image.size.width/image.size.height*HEIGHT>WIDTH) {
                _imaView.frame = CGRectMake(0, 0, WIDTH, image.size.height/image.size.width*WIDTH);
            }else{
                _imaView.frame = CGRectMake(0, 0, image.size.width/image.size.height*HEIGHT, HEIGHT);
            }
            
        }
        
        _imaView.center = CGPointMake(WIDTH/2, HEIGHT/2);
        
        self.navigationController.navigationBarHidden = YES;

    }];
    
}

- (void)hidIma
{
    _statusBarHidden = NO;
    [self prefersStatusBarHidden];
    self.navigationController.navigationBarHidden = NO;
    
    [UIView animateWithDuration:0.2 animations:^{
        
        _backView.alpha = 0;
    } completion:^(BOOL finished) {
        
        [_backView removeFromSuperview];
        
    }];
    
}

- (void)moveIma:(UIPanGestureRecognizer *)pan
{
    CGRect rect = pan.view.frame;
    
    CGPoint translation = [pan translationInView:_backView];
    if (pan.view.frame.size.height>HEIGHT) {
        
        pan.view.center = CGPointMake(pan.view.center.x,pan.view.center.y + translation.y);
    }
    if (pan.view.frame.size.width>WIDTH) {
        
        pan.view.center = CGPointMake(pan.view.center.x + translation.x, pan.view.center.y);
    }
    
    
    [pan setTranslation:CGPointZero inView:_backView];
    if (pan.state == UIGestureRecognizerStateEnded) {
        if (pan.view.frame.origin.y>0&pan.view.frame.size.height>HEIGHT) {
            
            
            [UIView animateWithDuration:0.5 animations:^{
                pan.view.frame = CGRectMake(pan.view.frame.origin.x, 0,pan.view.frame.size.width,pan.view.frame.size.height);
               
            }];
            
        }
        if ((rect.origin.y + rect.size.height)<HEIGHT&rect.size.height>HEIGHT) {
            [UIView animateWithDuration:0.5 animations:^{
                pan.view.frame = CGRectMake(pan.view.frame.origin.x, HEIGHT-rect.size.height,pan.view.frame.size.width,pan.view.frame.size.height);
                
            }];

        }
        if (pan.view.frame.origin.x>0&pan.view.frame.size.width>WIDTH) {
            [UIView animateWithDuration:0.5 animations:^{
                pan.view.frame = CGRectMake(0, pan.view.frame.origin.y,pan.view.frame.size.width,pan.view.frame.size.height);
                
            }];

        }
        if ((pan.view.frame.origin.x + rect.size.width)<WIDTH&pan.view.frame.size.width>WIDTH) {
            [UIView animateWithDuration:0.5 animations:^{
                pan.view.frame = CGRectMake(WIDTH - rect.size.width, pan.view.frame.origin.y,pan.view.frame.size.width,pan.view.frame.size.height);
                
            }];
            
        }
    }
}

- (void)pinch:(UIPinchGestureRecognizer *)pinch
{
    
    CGRect rect = pinch.view.frame;
    if (pinch.scale>2) {
       pinch.view.transform = CGAffineTransformScale(pinch.view.transform, pinch.scale, 2);
    }else{
        pinch.view.transform = CGAffineTransformScale(pinch.view.transform, pinch.scale, pinch.scale);
    }
    
   
    if (pinch.state == UIGestureRecognizerStateEnded) {

        if (rect.size.width<WIDTH) {
            
            if (rect.size.height<HEIGHT) {
                [UIView animateWithDuration:0.5 animations:^{
                    
                    pinch.view.center = CGPointMake(WIDTH/2 , HEIGHT/2);
                    
                    
                }];
                
            }else{
                [UIView animateWithDuration:0.5 animations:^{
                    
                    pinch.view.center = CGPointMake(WIDTH/2, rect.size.height/2);
                    
                }];
                }
        }
    }
    //每次缩放以后需要还原手势的倍数记录
    pinch.scale = 1;
}

- (void)saveIma
{
    if (_imaView.image) {
        UIImageWriteToSavedPhotosAlbum(_imaView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    
    if (error) {
        [_backView Message:@"保存失败" HiddenAfterDelay:1];
    }else{
        [_backView Message:@"保存成功" HiddenAfterDelay:1];
    }
}

//- (void)viewWillDisappear:(BOOL)animated
//{
//    NSLog(@"aaa");
//}

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    if (scrollView == _webView.scrollView) {
//        
//        
//        if (scrollView.contentOffset.y >= scrollView.contentSize.height - (HEIGHT - 64)) {
//            
//            NSLog(@"qqq");
//            scrollView.scrollEnabled = NO;
//            _table.scrollEnabled = YES;
//        }
//        
//    }else{
//        
//        if (scrollView.contentOffset.y <= 0) {
//            _webView.scrollView.scrollEnabled = YES;
//            _table.scrollEnabled = NO;
//        }
//    }
//    
//}

- (void)bannerViewFailToReceived:(NSError *)error
{
    
}
- (void)bannerViewWillClose
{
    _webView.height += GDTMOB_AD_SUGGEST_SIZE_320x50.height;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
